﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using Kingdee.BOS;
using Kingdee.BOS.Util;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Core.Report.PlugIn;
using Kingdee.BOS.Core.Report.PlugIn.Args;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Contracts.Report;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.DataEntity.Metadata.Service;


namespace LiMinCRMPlugin
{
    [Description("原药库存平衡表")]
    [Kingdee.BOS.Util.HotUpdate]
    public class RawMaterialInventoryReport : SysReportBaseService
    {
        /// <summary>
        /// 初始化
        /// </summary>
        public override void Initialize()
        {
            base.Initialize();
            // 简单账表类型：基本简单账表REPORTTYPE_NORMAL、
            ReportProperty.ReportType = ReportType.REPORTTYPE_NORMAL;
            //报表显示顺序字段
            //ReportProperty.IdentityFieldName = "FSTOCKID";
            //标识报表是否调用BuilderReportSqlAndTempTable接口创建临时表
            IsCreateTempTableByPlugin = true;

            ////联查单据
            //ReportProperty.BillKeyFieldName = "FMaterialId,";
            //ReportProperty.FormIdFieldName = "FFORMID";

            //设置精度控制
            List<DecimalControlField> list = new List<DecimalControlField>();
            //list.Add(new DecimalControlField("FPRICEDECIMAL", "FPRICE"));
            //ReportProperty.DecimalControlFieldList = list;

            // 是否支持分组汇总
            this.ReportProperty.IsGroupSummary = true;

            //仓库ID显示为仓库编码(需要报表数据源查询出来)
            //ReportProperty.DspInsteadColumnsInfo.DefaultDspInsteadColumns.Add("仓库", "仓库编码");
            //物料ID显示为物料编码(需要报表数据源查询出来)
            ReportProperty.DspInsteadColumnsInfo.DefaultDspInsteadColumns.Add("物料", "物料编码");

            //报表的列通过插件控制
            this.ReportProperty.IsUIDesignerColumns = false;

        }
        /// <summary>
        /// 向报表临时表，插入报表数据
        /// </summary>
        /// <param name="filter">过滤信息</param>
        /// <param name="tableName">临时表名</param>
        public override void BuilderReportSqlAndTempTable(IRptParams filter, string tableName)
        {
            base.BuilderReportSqlAndTempTable(filter, tableName);

            //小计行分组依据
            if (filter.FilterParameter.GroupbyString.Length > 0)
            {
                this.ReportProperty.GroupSummaryInfoData.DynamicFilterGroupbyString = filter.FilterParameter.GroupbyString;
            }

            //默认排序字段：需要从filter中取用户设置的排序字段
            //KSQL_SEQ: ROW_NUMBER() OVER(ORDER BY  {0} ) FIDENTITYID
            //排序字段
            string sortStr = filter.FilterParameter.SortString;
            KSQL_SEQ = string.Format(KSQL_SEQ, sortStr.IsNullOrEmptyOrWhiteSpace() ? " 仓库 asc" : sortStr);
            ////取值SQL
            //string sql = GetSql(filter);
            //sql = string.Format(@"SELECT T0.*,{0} INTO {1} FROM ({2})T0", KSQL_SEQ, tableName, sql);
            #region 条件
            string sql = @"EXEC RawMaterialInventory ";

            //添加条件过滤

            string filterStr = filter.FilterParameter.FilterString;
            if (!filterStr.IsNullOrEmptyOrWhiteSpace())
            {
                sql += string.Format("AND {0}", filterStr);
            }
            #endregion
            #region 获取快捷过滤
            StringBuilder sql1 = new StringBuilder();
            var custFilter = filter.FilterParameter.CustomFilter;
            ////多选基础资料取值(物料)
            //DynamicObjectCollection dyCollection = custFilter["F_QLTK_MulMaterial"] as DynamicObjectCollection;
            //string MulMaterialID = string.Empty;
            ////循环获取物料信息
            //foreach (DynamicObject dobj in dyCollection)
            //{
            //    DynamicObject d = dobj["F_QLTK_MulMaterial"] as DynamicObject;
            //    if (MulMaterialID.IsEmpty())
            //    {
            //        MulMaterialID = d["id"].ToString();
            //    }
            //    else
            //    {
            //        MulMaterialID = MulMaterialID + "," + d["id"].ToString() ;
            //    }
            //}
            //多选基础资料取值(仓库)
            DynamicObjectCollection ckCollection = custFilter["F_QLTK_MulStock"] as DynamicObjectCollection;
            string MulStockID = string.Empty;
            //循环获取物料信息
            foreach (DynamicObject dobj in ckCollection)
            {
                DynamicObject d = dobj["F_QLTK_MulStock"] as DynamicObject;
                if (MulStockID.IsEmpty())
                {
                    MulStockID =  d["id"].ToString();
                }
                else
                {
                    MulStockID = MulStockID + "," + d["id"].ToString();
                }
            }
            //MulMaterialID = MulMaterialID.TrimEnd(',');
            MulStockID = MulStockID.TrimEnd(',');
            DynamicObject lstDyn = custFilter["F_QLTK_Material"] as DynamicObject;
            DynamicObject lstDyn1 = custFilter["F_QLTK_Stock"] as DynamicObject;
            DynamicObject lstDyn2 = custFilter["F_QLTK_OrgId"] as DynamicObject;
            sql1.AppendFormat(" @tempFilterTable='{0}', ", tableName);
            sql1.AppendFormat(" @KSQL_SEQ='{0}', ", KSQL_SEQ);          
            //sql1.AppendFormat(" @Material='{0}' , ", MulMaterialID);
            sql1.AppendFormat(" @Warehouse='{0}' , ", MulStockID);
            sql1.AppendFormat(" @Org={0} ", lstDyn2["ID"].ToString());

          



            #endregion
            sql += sql1.ToString();


            DBUtils.Execute(Context, sql);
        }

        protected virtual string GetSql(IRptParams filter)
        {
            string sql = @"EXEC RawMaterialInventory ";

            //添加条件过滤
            string filterStr = filter.FilterParameter.FilterString;
            if (!filterStr.IsNullOrEmptyOrWhiteSpace())
            {
                sql += string.Format("AND {0}", filterStr);
            }
            return sql;
        }
        /// <summary>
        /// 表头字段
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public override ReportHeader GetReportHeaders(IRptParams filter)
        {
            ReportHeader header = base.GetReportHeaders(filter);
            header.AddChild("仓库", new LocaleValue("仓库"));
            header.AddChild("类别", new LocaleValue("类别"));
            header.AddChild("物料", new LocaleValue("物料"));
            header.AddChild("名称", new LocaleValue("名称"));
            header.AddChild("库存量", new LocaleValue("库存量"), SqlStorageType.SqlDecimal);
            header.AddChild("计划量", new LocaleValue("计划量"), SqlStorageType.SqlDecimal);
            header.AddChild("已入库", new LocaleValue("已入库"), SqlStorageType.SqlDecimal);
            header.AddChild("未入库", new LocaleValue("库存未入库量"), SqlStorageType.SqlDecimal);
            header.AddChild("原药订单预留", new LocaleValue("原药订单预留"), SqlStorageType.SqlDecimal);
            header.AddChild("制剂订单预留", new LocaleValue("制剂订单预留"), SqlStorageType.SqlDecimal);
            header.AddChild("剩余库存", new LocaleValue("剩余库存"), SqlStorageType.SqlDecimal);

            return header;
        }


     


        public override ReportTitles GetReportTitles(IRptParams filter)
        {
            var result = base.GetReportTitles(filter);
            if (result == null)
            {
                result = new ReportTitles();
            }
            DynamicObject customFilter = filter.FilterParameter.CustomFilter;
            DynamicObject Org = customFilter["F_QLTK_OrgId"] as DynamicObject;
            DynamicObject Material = customFilter["F_QLTK_Material"] as DynamicObject;
            DynamicObject Stock = customFilter["F_QLTK_Stock"] as DynamicObject;
            string OrgValues = customFilter["F_QLTK_OrgId_id"].ToString();
            string MaterialValues = customFilter["F_QLTK_Material_id"].ToString();
            string StockValues = customFilter["F_QLTK_Stock_id"].ToString();
            //多选基础资料取值(物料)
            //DynamicObjectCollection dyCollection = customFilter["F_QLTK_MulMaterial"] as DynamicObjectCollection;
            //string MulMaterialName = string.Empty;
            ////循环获取物料信息
            //foreach (DynamicObject dobj in dyCollection)
            //{
            //    DynamicObject d = dobj["F_QLTK_MulMaterial"] as DynamicObject;
            //    if (MulMaterialName.IsEmpty())
            //    {
            //        MulMaterialName = d["Name"].ToString();
            //    }
            //    else
            //    {
            //        MulMaterialName = MulMaterialName + "," + d["Name"].ToString();
            //    }
            //}
            //多选基础资料取值(仓库)
            DynamicObjectCollection ckCollection = customFilter["F_QLTK_MulStock"] as DynamicObjectCollection;
            string MulStockName = string.Empty;
            //循环获取物料信息
            foreach (DynamicObject dobj in ckCollection)
            {
                DynamicObject d = dobj["F_QLTK_MulStock"] as DynamicObject;
                if (MulStockName.IsEmpty())
                {
                    MulStockName = d["Name"].ToString();
                }
                else
                {
                    MulStockName = MulStockName + "," + d["Name"].ToString();
                }
            }

            result.AddTitle("F_QLTK_OrgIdText", Org["Name"].ToString());
            //result.AddTitle("F_QLTK_MaterialText", MulMaterialName);
            result.AddTitle("F_QLTK_StockText", MulStockName);

            return result;
        }


        /// <summary>
        /// 设置报表合计列
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public override List<SummaryField> GetSummaryColumnInfo(IRptParams filter)
        {
            var result = base.GetSummaryColumnInfo(filter);
            result.Add(new SummaryField("库存量", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("计划量", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("已入库", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("未入库", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("原药订单预留", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("制剂订单预留", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("剩余库存", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            return result;
        }


    }
}
